﻿using System;

namespace SMARTMobile.WinPhone
{
    
    public class CommandRoute : ICommandRoute
    {
        public Action<object> ExecuteHandler { get; set; }
        public Func<object, bool> CanExecuteHandler { get; set; }

        private readonly string _pagename;
        private bool _here;
        private static readonly object SyncRoot = new object();

        public CommandRoute()
        {
        }

        public CommandRoute(string pagename)
        {
            _pagename = pagename;
            ExecuteHandler = Navigate;
        }

        #region ICommandRoute Members

        public bool CanExecute(object parameter)
        {
            lock (SyncRoot)
            {
                if (_here) return false;
                return null == CanExecuteHandler || CanExecuteHandler(parameter);
            }
        }

        public void Execute(object parameter)
        {
            lock (SyncRoot)
            {
                if (_here) return;
                _here = true;

                if (null == ExecuteHandler)
                {
                    _here = false;
                    return;
                }
                RaiseCanExecuteChanged();
                ExecuteHandler(parameter);
            }
        }

        public event EventHandler CanExecuteChanged;

        public void RaiseCanExecuteChanged(bool allow)
        {
            lock (SyncRoot)
            {
                _here = !allow;
            }
            RaiseCanExecuteChanged();
        }

        public void RaiseCanExecuteChanged()
        {
            if(null != CanExecuteChanged)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }

        #endregion

        private void Navigate(object parameter)
        {
            PageNavigationService.Current.Navigate(_pagename);
        }
    }
}